package com.cn.androidpicker.utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;


import com.cn.androidpicker.R;
import com.cn.androidpicker.bean.CityData;
import com.cn.androidpicker.bean.DistrictData;
import com.cn.androidpicker.bean.ProvincesData;
import com.cn.androidpicker.bean.TownData;
import com.cn.pickerview.builder.OptionsPickerBuilder;
import com.cn.pickerview.listener.CustomListener;
import com.cn.pickerview.listener.OnOptionsSelectListener;
import com.cn.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @ProjectName: Rxlifecycle
 * @Packge: com.cn.rxlifecycle.utils
 * @Description: 地址选择
 * @CreateDate: 2021/6/18 0018 16:42
 */
public class CitySelectUtils {

    private OptionsPickerView cityOptionsPickerView;
    private OnAddressChoosedListener onAddressChoosedListener;


    private Context context;

    public CitySelectUtils(Context context) {
        this.context = context;
    }

    public void startShowChooseDialog() {

        /*
         * 被观察者
         * */
        Observable observable = Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(@NonNull ObservableEmitter e) throws Exception {
                initCityData(context);
                e.onNext("");
                e.onComplete();
            }

        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
        /*
         * 观察者者
         * */
        Observer observer = new Observer() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                Log.i("addr", "地址数据开始解析");
                Toast.makeText(context,"地址数据正在解析，请耐心等待...",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(@NonNull Object o) {
                Log.e("收到onnext", "地址数据获取成功");
                showPickerView(context);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                e.printStackTrace();
                Log.i("addr", "地址数据获取失败");
            }

            @Override
            public void onComplete() {
                Log.e("完成", "===");
            }
        };
        observable.subscribe(observer);

    }

    public interface OnAddressChoosedListener {
        public void onChoosed(ProvincesData provinceBean, CityData cityBean, DistrictData districtBean, TownData townData);

        public void onAddressChoosed(String address);
    }

    public void setOnAddressChoosedListener(OnAddressChoosedListener onAddressChoosedListener) {
        this.onAddressChoosedListener = onAddressChoosedListener;
    }


    private List<ProvincesData> optionsProvinces = new ArrayList<>();
    private ArrayList<ArrayList<CityData>> optionsCitys = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<DistrictData>>> optionsDistricts = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<ArrayList<TownData>>>> optionsTowns = new ArrayList<>();

    private void initCityData(Context context) {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //获取assets目录下的json文件数据
        String JsonData = new GetJsonDataUtil().getJson(context, "myprovince.json");
        //用Gson 转成实体
        ArrayList<ProvincesData> provinceBeans = parseData(JsonData);

        //第一级
        optionsProvinces.addAll(provinceBeans);
        //遍历省份
        for (int i = 0; i < optionsProvinces.size(); i++) {
            //该省的城市列表（第二级）
            ArrayList<CityData> cityData = new ArrayList<>();
            cityData.addAll(optionsProvinces.get(i).getChildren());
            optionsCitys.add(cityData);

            //该省的所有地区列表（第三极）
            ArrayList<ArrayList<DistrictData>> districtDatas = new ArrayList<>();
            //该省的所有地区列表（第四极）
            ArrayList<ArrayList<ArrayList<TownData>>> townDatas = new ArrayList<>();

            for (int j = 0; j < optionsProvinces.get(i).getChildren().size(); j++) {
                ArrayList<DistrictData> districtList = new ArrayList<>();//该城市的所有地区列表
                districtList.addAll(optionsProvinces.get(i).getChildren().get(j).getChildren());
                districtDatas.add(districtList);
                ArrayList<ArrayList<TownData>> townLists = new ArrayList<>();
                if (optionsProvinces.get(i).getChildren().get(j).getChildren() != null || optionsProvinces.get(i).getChildren().get(j).getChildren().size() != 0) {
                    for (int k = 0; k < optionsProvinces.get(i).getChildren().get(j).getChildren().size(); k++) {
                        ArrayList<TownData> townData = new ArrayList<>();
                        townData.addAll(optionsProvinces.get(i).getChildren().get(j).getChildren().get(k).getChildren());
                        townLists.add(townData);
                    }
                }
                townDatas.add(townLists);
            }
            optionsTowns.add(townDatas);
            optionsDistricts.add(districtDatas);
        }


    }

    public ArrayList<ProvincesData> parseData(String result) {
        ArrayList<ProvincesData> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProvincesData entity = gson.fromJson(data.optJSONObject(i).toString(), ProvincesData.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


    public void showPickerView(Context context) {
        cityOptionsPickerView = new OptionsPickerBuilder(context, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, int options4, View v) {
                //返回的分别是三个级别的选中位置
//                String tx = optionsCitys.get(options1).getPickerViewText() +
//                        optionsProvinces.get(options1).get(options2) +
//                        optionsAreas.get(options1).get(options2).get(options3);

                String tx = optionsProvinces.get(options1).getName() + " " + optionsProvinces.get(options1).getChildren().get(options2).getName() + " " + optionsProvinces.get(options1).getChildren().get(options2).getChildren().get(options3).getName() + " " + optionsProvinces.get(options1).getChildren().get(options2).getChildren().get(options3).getChildren().get(options4).getName();
                if (onAddressChoosedListener != null) {
                    onAddressChoosedListener.onChoosed(optionsProvinces.get(options1), optionsProvinces.get(options1).getChildren().get(options2), optionsProvinces.get(options1).getChildren().get(options2).getChildren().get(options3), optionsProvinces.get(options1).getChildren().get(options2).getChildren().get(options3).getChildren().get(options4));
                    onAddressChoosedListener.onAddressChoosed(tx);
                }
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_city, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                cityOptionsPickerView.returnData();
                                cityOptionsPickerView.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                cityOptionsPickerView.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setDividerColor(Color.TRANSPARENT)
                .setTextColorOut(0xFF999999)
                //设置选中项文字背景颜色
                .setCenterBgColor(0xfffafafa)
                //设置选中项文字颜色
                .setTextColorCenter(0xFF222222)
                .setContentTextSize(18)
                .setLineSpacingMultiplier(2.5f)
//                .setTextXOffset(40, 0, 0, -40)
                .build();
//        一级选择器
//        cityOptionsPickerView.setPicker(optionsProvinces);
//        //二级选择器
//        cityOptionsPickerView.setPicker(provinces, citys);
//        //三级选择器
//        cityOptionsPickerView.setPicker(optionsProvinces, optionsCitys, optionsDistricts);
        //四级选择器
        cityOptionsPickerView.setPicker(optionsProvinces, optionsCitys, optionsDistricts, optionsTowns);

        Dialog dialog = cityOptionsPickerView.getDialog();
        if (dialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM
            );
            params.leftMargin = 0;
            params.rightMargin = 0;
            cityOptionsPickerView.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = dialog.getWindow();
            if (dialogWindow != null) {
                //修改动画样式
                dialogWindow.setWindowAnimations(R.style.picker_view_slide_anim);
                //改成Bottom,底部显示
                dialogWindow.setGravity(Gravity.BOTTOM);
            }
        }
        cityOptionsPickerView.show();
    }


}
